﻿using HCQ2_Common;
using HCQ2_IDAL;
using HCQ2_Model;
using HCQ2_Model.DocModel;
using HCQ2_Model.DocModel.APIModel;
using HCQ2_Model.DocModel.APIResultModel;
using HCQ2_Model.Pay;
using HCQ2_Model.ViewModel;
using HCQ2_Model.VR.Model;
using HCQ2_Model.VR.Params;
using HCQ2_Model.VRDD.InputDto._0730;
using HCQ2_Model.VRDD.InputDto._210908;
using HCQ2_Model.VRDD.OutputDto._0730;
using HCQ2_Model.VRDD.OutputDto._210908;
using HCQ2_Model.VRDevice.ParamModel;
using HCQ2_Model.VRDevice.ResultModel;
using HCQ2_Model.VRQDMeta.OutputDto;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace HCQ2_BLL
{
    public partial class T_DocumentInfoBLL:HCQ2_IBLL.IT_DocumentInfoBLL
    {
        //*******************************************奇点元宇宙***********************************************
        /// <summary>
        ///  获取奇点元宇宙【应用】列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <param name="total">返回总条数</param>
        /// <returns></returns>
        public List<MetaListResult> GetQDMetaList(QDMetaParam param, out int total)
        {
            var list = DBSession.IT_DocumentInfoDAL.GetQDMetaList(param, out total);
            list?.ForEach(s =>
            {
                if (s.finish_time > 0)
                    s.finishSpan = Math.Round((decimal)s.finish_time / 60 / 60, 2);            
            });
            return list;
        }
        /// <summary>
        ///  获取数据
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public MetaListResult GetProgramData(int file_id)
        {
            var obj= DBSession.IT_DocumentInfoDAL.GetProgramData(file_id);
            if (obj.finish_time > 0)
                obj.finishSpan = Math.Round((decimal)obj.finish_time / 60 / 60, 2);
            return obj;
        }
        /// <summary>
        ///  获取奇点元宇宙【房间】列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <param name="total">返回总条数</param>
        /// <returns></returns>
        public List<MetaRoomResult> GetQDMetaRoomList(QDMetaParam param, out int total)
        {
            return DBSession.IT_DocumentInfoDAL.GetQDMetaRoomList(param, out total);
        }
        /// <summary>
        ///  获取数据【房间】
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public MetaRoomResult GetRoomData(int file_id)
        {
            return DBSession.IT_DocumentInfoDAL.GetRoomData(file_id);
        }
        //*******************************************VR设备***********************************************
        /// <summary>
        ///  获取楼宇列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <param name="total">返回总条数</param>
        /// <returns></returns>
        public List<VRBuildResult> GetVRBuildList(VRdeviceParam param, out int total)
        {
            return DBSession.IT_DocumentInfoDAL.GetVRBuildList(param, out total);
        }
        /// <summary>
        ///  获取设备类别
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <param name="total">返回总条数</param>
        /// <returns></returns>
        public List<VRdeviceResult> GetVRDeviceList(VRdeviceParam param, out int total)
        {
            return DBSession.IT_DocumentInfoDAL.GetVRDeviceList(param,out total);
        }
        /// <summary>
        ///  获取设备信息
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public VRdeviceResult GetVRDevicePrice(int file_id)
        {
            return DBSession.IT_DocumentInfoDAL.GetVRDevicePrice(file_id);
        }
        /// <summary>
        ///  导入设备
        /// </summary>
        /// <param name="tempPath"></param>
        /// <returns></returns>
        public List<string> importDevice(string tempPath, out bool importMark)
        {
            importMark = false;
            //获取导入文件里面的数据
            Stopwatch sw = new Stopwatch();
            sw.Start();
            List<string> valid = new List<string>();
            DataTable excelData = NpoiHelper.ExcelToDataTable(tempPath, true, 0);//读取第一个sheet(设备主表)
            DataTable excelPrice = NpoiHelper.ExcelToDataTable(tempPath, true, 1);//读取第二个sheet(设备价格表)
            if (excelData == null)
                valid.Add("无法获取到【设备主表】文件中数据");
            if(excelPrice==null)
                valid.Add("无法获取到【设备价格表】文件中数据");
            sw.Stop();
            if (valid.Count > 0)
                return valid;
            List<DevicePortModel> folderPaths;//导航树信息
            //验证设备主表
            valid = checkRequired(excelData,out folderPaths);
            if (valid.Count > 0)
                return valid;
            //验证设备价格表
            valid = checkPriceRequired(excelPrice);
            if (valid.Count > 0)
                return valid;
            //封装List
            List<T_DocumentInfo> list = toImportModelTable(excelData);
            List<T_VRGoodDisiPrice> priceList = toImportPriceModelTable(excelPrice);
            sw.Restart();
            //写入设备表、关系表、价格明细表
            list.ForEach(o=> {
                //1.0 添加主表
                DBSession.IT_DocumentInfoDAL.Add(o);
                //1.1 添加设备导航关系
                DevicePortModel paramPath = folderPaths.Where(s => s.file_code.Equals(o.file_code)).FirstOrDefault();
                T_DocumentFolderRelation relation = new T_DocumentFolderRelation
                {
                    file_id = o.file_id,
                    folder_id = (paramPath == null) ? 0 : paramPath.folder_id,
                    folder_path = (paramPath == null) ? "" : paramPath.folder_path,
                    create_id = HCQ2UI_Helper.OperateContext.Current.Usr.user_id
                };
                DBSession.IT_DocumentFolderRelationDAL.Add(relation);
                //1.2 添加价格明细
                List<T_VRGoodDisiPrice> _prices = priceList.Where(s => s.file_code.Equals(o.file_code))?.ToList();
                _prices.ForEach(s=> {
                    DBSession.IT_VRGoodDisiPriceDAL.Add(new T_VRGoodDisiPrice {
                        op_code = Helper.GetGuid,
                        file_code = o.file_code,
                        file_id = o.file_id,
                        op_month = s.op_month,
                        ori_price = s.ori_price,
                        price_name = s.price_name,
                        price_type = 1
                    });
                });
            });
            sw.Stop();
            importMark = true;
            return valid;
        }
        /// <summary>
        /// 验证：设备主表 必填信息是否为空
        /// </summary>
        /// <param name="excelData"></param>
        /// <returns></returns>
        private List<string> checkRequired(DataTable excelData,out List<DevicePortModel> folderPaths)
        {
            List<string> valid = new List<string>();
            folderPaths = new List<DevicePortModel>();
            string tableName = "设备主表：";
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                //1.0 判断必填项是否为空
                int rowNum = (i + 1 + 1);
                string fileCode = Convert.ToString(excelData.Rows[i]["F1"]);
                if (fileCode == null || string.IsNullOrEmpty(fileCode))
                    valid.Add($"{tableName}第{rowNum}行，设备代码不允许为空！");
                else if (excelData.Rows[i]["F2"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F2"])))
                    valid.Add($"{tableName}第{rowNum}行，设备名称不允许为空！");
                else if (excelData.Rows[i]["F3"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F3"])))
                    valid.Add($"{tableName}第{rowNum}行，设备所属目录不允许为空！");
                else if (excelData.Rows[i]["F4"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F4"])))
                    valid.Add($"{tableName}第{rowNum}行，二维码内容不允许为空！");
                //2.0 判断是否存在：代码
                int fileCount = 0;
                if (!string.IsNullOrEmpty(fileCode))
                    fileCount = DBSession.IT_DocumentInfoDAL.SelectCount(o => o.file_code.Equals(fileCode) && o.file_status == 5 && !o.if_remove);
                if (fileCount > 0)
                    valid.Add($"{tableName}第{rowNum}行，代码：【{fileCode}】在系统中已存在！");
                //3.0 所属目录是否存在
                string folderPath= Convert.ToString(excelData.Rows[i]["F3"]);
                if (!string.IsNullOrEmpty(folderPath))
                {
                    var queryPath = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_path.Equals(folderPath));
                    if (queryPath == null)
                        valid.Add($"{tableName}第{rowNum}行，填写的所属目录：【{folderPath}】在系统中不存在！");
                    else
                        folderPaths.Add(new DevicePortModel { file_code = fileCode, folder_id = queryPath.folder_id, folder_path = queryPath.folder_path });
                }
            }
            return valid;
        }
        /// <summary>
        ///  验证：设备价格表 必填信息是否为空
        /// </summary>
        /// <param name="excelData"></param>
        /// <returns></returns>
        private List<string> checkPriceRequired(DataTable excelData)
        {
            List<string> valid = new List<string>();
            string tableName = "设备价格表：";
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                //1.0 判断必填项是否为空
                int rowNum = (i + 1 + 1);
                string fileCode = Convert.ToString(excelData.Rows[i]["F1"]);
                if (fileCode == null || string.IsNullOrEmpty(fileCode))
                    valid.Add($"{tableName}第{rowNum}行，代码不允许为空！");
                else if (excelData.Rows[i]["F2"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F2"])))
                    valid.Add($"{tableName}第{rowNum}行，价格名称不允许为空！");
                else if (excelData.Rows[i]["F3"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F3"])))
                    valid.Add($"{tableName}第{rowNum}行，时长不允许为空！");
                else if (excelData.Rows[i]["F4"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F4"])))
                    valid.Add($"{tableName}第{rowNum}行，金额不允许为空！");
            }
            return valid;
        }
        /// <summary>
        ///  数据转换为导入的数据
        /// </summary>
        /// <param name="excelData">原始数据</param>
        /// <returns></returns>
        private List<T_DocumentInfo> toImportModelTable(DataTable excelData)
        {
            List<T_DocumentInfo> list = new List<T_DocumentInfo>();
            T_User user = HCQ2UI_Helper.OperateContext.Current.Usr;
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                list.Add(new T_DocumentInfo
                {
                    file_name = Helper.ToString(excelData.Rows[i]["F2"]),
                    file_code = Helper.ToString(excelData.Rows[i]["F1"]),
                    file_note = Helper.ToString(excelData.Rows[i]["F5"]),
                    file_order = Helper.ToInt(excelData.Rows[i]["F6"]),
                    qr_code = Helper.ToString(excelData.Rows[i]["F4"]),
                    file_status = 5,
                    file_classify = "",
                    doc_type = "",
                    folder_num = "",
                    page_type = "VRDevice",
                    create_time = DateTime.Now,
                    create_id = user.user_id,
                    create_name = user.user_name,
                    update_name = user.user_name,
                    update_time = DateTime.Now
                });
            }
            return list;
        }
        /// <summary>
        ///  数据转换为导入的数据
        /// </summary>
        /// <param name="excelData">原始数据</param>
        /// <returns></returns>
        private List<T_VRGoodDisiPrice> toImportPriceModelTable(DataTable excelData)
        {
            List<T_VRGoodDisiPrice> list = new List<T_VRGoodDisiPrice>();
            T_User user = HCQ2UI_Helper.OperateContext.Current.Usr;
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                list.Add(new T_VRGoodDisiPrice
                {
                    op_code = Helper.GetGuid,
                    file_code = Helper.ToString(excelData.Rows[i]["F1"]),
                    file_id = 0,
                    op_month = Helper.ToInt(excelData.Rows[i]["F3"]),
                    ori_price = Helper.ToDecimal(excelData.Rows[i]["F4"]),
                    price_name = Helper.ToString(excelData.Rows[i]["F2"]),
                    price_type = 1
                });
            }
            return list;
        }
        //********************************************end*************************************************
        /// <summary>
        ///  添加文档
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddDocInfo(T_DocumentInfo model)
        {
            if (null == model)
                return 0;
            int mark = Add(model);
            if (mark > 0)
                return model.file_id;
            return 0;
        }
        /// <summary>
        ///  获取Table数据
        /// </summary>
        /// <param name="model">参数</param>
        /// <param name="total">根据条件返回记录条数</param>
        /// <returns></returns>
        public List<DocTreeResultModel> GetTableData(HeadTableParamModel model, out int total)
        {
            total = 0;
            if (null == model)
                return null;
            List<DocTreeResultModel> list = new List<DocTreeResultModel>();
            IT_DocumentInfoDAL dal = DBSession.IT_DocumentInfoDAL;
            list = dal.GetProTableList(model);
            total = dal.GetProCount(model);
            return list;
        }
        /// <summary>
        ///  获取Table数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<DocTreeResultModel> GetTableData(DocTableParamModel model, int user_id, out int total)
        {
            total = 0;
            if (null == model)
                return null;
            List<DocTreeResultModel> list = new List<DocTreeResultModel>();
            IT_DocumentInfoDAL dal = DBSession.IT_DocumentInfoDAL;
            switch (model.pageType)
            {
                case 1: {
                        //我的分享
                        list = dal.GetTableByOwnShareDoc(model, user_id);
                        total = dal.GetTableByOwnShareDocCount(model, user_id);
                    } break;
                case 2: {
                        //我的收藏
                        list = dal.GetTableShareByOwnDoc(model, user_id);
                        total = dal.GetTableShareByOwnDocCount(model, user_id);
                    }  break;
                case 3: {
                        //公用文档
                        list = dal.GetTablePublicDoc(model, user_id, 5);
                        total = dal.GetTablePublicDocCount(model, user_id, 5);
                    } break;
                case 4: {
                        //回收站
                        list = dal.GetTableRemoveDoc(model, user_id);
                        total = dal.GetTableRemoveDocCount(model, user_id);
                    } break;
                case 5: {
                        //待审核资源
                        list=dal.GetTableApproveDoc(model, user_id, HCQ2UI_Helper.OperateContext.Current.Usr.unit_code);
                        total = dal.GetTableApproveDocCount(model, user_id, HCQ2UI_Helper.OperateContext.Current.Usr.unit_code);
                    } break;
                case 6: {
                        //共享文档(免费下载)
                        List<int> roles = HCQ2UI_Helper.Session.SysPermissSession.RolesList;
                        list = dal.GetPublicDocOrShare(model, user_id, roles);
                        total = dal.GetPublicDocOrShareCount(model, user_id, roles);
                    }
                    break;
                default: {
                        //我的文档
                        list = dal.GetTableByOwnDoc(model, user_id);
                        total = dal.GetTableByOwnDocCount(model, user_id);
                    } break;
            }
            if (null == list)
                return null;
            return list;
        }
        /// <summary>
        ///  获取用户当天上传数据
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="modelType">模块类别</param>
        /// <returns></returns>
        public int GetUpNumByUser(int user_id, string modelType)
        {
            return DBSession.IT_DocumentInfoDAL.GetUpNumByUser(user_id, modelType);
        }

        /// <summary>
        ///  根据代码获取字典下拉
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<ResultSelectVal> GetDocDictByCode(SelectKeyModel code)
        {
            return DBSession.IT_DocumentInfoDAL.GetDocDictByCode(code);
        }
        /// <summary>
        ///  批量编辑作品
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="folder_id"></param>
        /// <param name="folder_path"></param>
        /// <param name="file_classify"></param>
        /// <param name="org_unit"></param>
        /// <returns></returns>
        public int SaveBatchFile(string fileId, string file_classify, string org_unit,string unit_name)
        {
            return DBSession.IT_DocumentInfoDAL.SaveBatchFile(fileId, file_classify, org_unit,unit_name);
        }

        //************************************APP接口************************************
        /// <summary>
        ///  获取商品详情接口
        /// </summary>
        /// <param name="file_id"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public GoodsDetal GetAppGoodsDetail(int file_id, int user_id = 0)
        {
            //1.0 获取商品基本信息
            GoodsListModel o = DBSession.IT_DocumentInfoDAL.GetAPPGoodsDetail(file_id, user_id);
            if (o == null)
                return null;
            DateTime dtNow = DateTime.Now;
            //商品详情
            GoodsDetal goods = new GoodsDetal
            {
                minPrice = o.minPrice,
                maxPrice = o.maxPrice,
                appSize = o.appSize,
                appID = o.appID,
                playerNum = o.playerNum,
                timeSpan = (o.finish_time > 0) ? Math.Round((decimal)o.finish_time / 60 / 60, 2) : 0,
                isSoldOut = o.isSoldOut,
                pay_num = o.pay_num,
                disDay = dtNow >= o.pdate ? (dtNow - o.pdate).Days : 0,
                proDate = o.proDate,
                pdate = o.pdate,//原始
                doc_number = o.doc_number,
                gps_x = o.gps_x,
                gps_y = o.gps_y,
                voice_num = o.voice_num,
                pimage_num = o.pimage_num,
                is_mian = o.is_mian,
                is_batch = o.is_batch,
                rate = o.rate,
                store_id = o.store_id,
                store_name = o.store_name,
                founder_id = o.founder_id,
                founder_name = o.founder_name,
                store_top = o.store_top,
                store_url = (!string.IsNullOrEmpty(o.store_url)) ? o.store_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "",//商铺缩略图
                image_num = o.image_num,
                video_num = o.video_num,
                works_num = o.works_num,
                is_entity = o.is_entity,
                out_link = o.out_link,
                folder_name = o.folder_name,
                qr_code = o.qr_code,
                file_order = o.file_order,
                learn_num = o.learn_num,
                topic_num = o.topic_num,
                result_ok = o.result_ok,
                result_error = o.result_error,
                pageType = o.pageType,
                file_code = o.file_code,
                org_unit = o.org_unit,
                file_id = o.file_id,
                file_name = o.file_name,
                file_note = o.file_note,
                is_recommend = o.is_recommend,
                alias_name = o.alias_name,
                //file_money = o.file_money,
                vr_star = o.vr_star,
                self_star = o.self_star,
                file_classify = o.file_classify,
                is_get = o.is_get,
                is_hold = o.is_hold,
                create_time = o.create_time,
                create_name = o.create_name,
                create_id = o.create_id,
                browse_num = o.browse_num,
                hold_num = o.hold_num,
                down_number = o.down_number,
                talk_num = o.talk_num,
                file_status = o.file_status,
                spread_url = o.spread_url,
                video_url = o.video_url,
                folder_limit = o.folder_limit,
                pro_form = o.pro_form,
                isPay = o.isPay,
                isfree = o.isfree,
                folder_author = o.folder_author,
                update_time = o.update_time,
                share_num = o.share_num,
                allow_edit = o.allow_edit,
                option_size = o.option_size,
                proType = o.proType,
                supplyType = o.supplyType,
                approve_time = o.approve_time,
                folder_id = o.folder_id,
                folder_pro_type = o.folder_pro_type,
                works_pro_type = o.works_pro_type,
                picture_id = o.picture_id,
                approve_note = o.approve_note
            };
            if (!string.IsNullOrEmpty(o.user_head))
                goods.user_head = o.user_head?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            if (!string.IsNullOrEmpty(o.picture))
                goods.picture = o.picture?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            //原始价格列表
            List<GoodsPriceModel> price = new List<GoodsPriceModel>();
            //折扣价格表
            List<GoodsPriceModel> ratePrice = new List<GoodsPriceModel>();
            //附件列表
            List<GoodsFileOption> files = new List<GoodsFileOption>();
            //1.2 原始商品价格列表
            List<T_VRGoodDisiPrice> _price = DBSession.IT_VRGoodDisiPriceDAL.Select(s => s.file_id == file_id);
            //1.3 原始附件列表
            List<T_DocFileOptions> _files = DBSession.IT_DocFileOptionsDAL.Select(s => s.file_id == file_id);
            //缩略图列表
            List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == file_id);
            if (photoOption.Count > 0)
                photoOption.ForEach(s => s.file_url = s.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
            goods.photoOption = photoOption;
            //1.2.1 处理价格模型
            _price.ForEach(s => 
            {
                decimal tempPrice = s.ori_price;
                price.Add(new GoodsPriceModel { PurchasePeriodCode = s.op_code, price_name = s.price_name, op_month = s.op_month, op_price = s.ori_price });
                if (goods.rate > 0 && goods.rate <= 10)
                    tempPrice = Math.Round(tempPrice * goods.rate / 10, 2);
                ratePrice.Add(new GoodsPriceModel { PurchasePeriodCode = s.op_code, price_name = s.price_name, op_month = s.op_month, op_price = tempPrice });
            });
            //1.3.1 处理附件模型
            _files.ForEach(s => files.Add(new GoodsFileOption { option_id = s.option_id, head_facility = s.head_facility, option_name = s.option_name, option_type = s.option_type, option_size = s.option_size, option_note = s.option_note, option_plat = s.option_plat, service_id = s.service_id, file_suffix = s.file_suffix }));
            if(_files.Count>0)
                goods.prefixUrl = GetServiceUrl(_files.FirstOrDefault().service_id);
            goods.files = files;
            goods.price = price;
            goods.ratePrice = ratePrice;
            if (price.Count > 0)
                goods.file_money = price.FirstOrDefault().op_price;
            return goods;
        }
        /// <summary>
        ///  获取商品列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public TableModel GetAPPShopList(ViewGoodsModel model, int userId)
        {
            int total;
            List<GoodsListModel> result = DBSession.IT_DocumentInfoDAL.GetAPPShopList(model, userId, out total);
            List<int> fileIds = result.Select(s => s.file_id)?.ToList();
            List<GoodsModel> goods = new List<GoodsModel>();
            if (fileIds != null && fileIds.Count>0)
            {
                string temp = string.Join(",", fileIds.ToArray());
                List<T_VRGoodDisiPrice> query = DBSession.IT_VRGoodDisiPriceDAL.Select(s => temp.Contains(s.file_id.ToString()));
                result.ForEach(o =>
                {
                    GoodsModel m = new GoodsModel
                    {
                        doc_number=o.doc_number,
                        gps_x =o.gps_x,
                        gps_y=o.gps_y,
                        voice_num=o.voice_num,
                        pimage_num=o.pimage_num,
                        is_mian=o.is_mian,
                        is_batch=o.is_batch,
                        rate =o.rate,
                        store_id=o.store_id,
                        store_name=o.store_name,
                        founder_id=o.founder_id,
                        founder_name=o.founder_name,
                        store_top=o.store_top,
                        store_url = (!string.IsNullOrEmpty(o.store_url)) ? o.store_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "",//商铺缩略图
                        image_num =o.image_num,
                        video_num=o.video_num,
                        works_num=o.works_num,
                        is_entity = o.is_entity,
                        out_link = o.out_link,
                        folder_name = o.folder_name,
                        qr_code = o.qr_code,
                        learn_num = o.learn_num,
                        topic_num = o.topic_num,
                        result_ok = o.result_ok,
                        result_error = o.result_error,
                        file_order = o.file_order,
                        pageType = o.pageType,
                        file_code = o.file_code,
                        org_unit = o.org_unit,
                        file_id = o.file_id,
                        file_name = o.file_name,
                        is_recommend = o.is_recommend,
                        alias_name = o.alias_name,
                        file_note = o.file_note,
                        //file_money = o.file_money,
                        vr_star = o.vr_star,
                        self_star = o.self_star,
                        file_classify = o.file_classify,
                        is_get = o.is_get,
                        is_hold = o.is_hold,
                        create_time = o.create_time,
                        create_name = o.create_name,
                        create_id = o.create_id,
                        browse_num = o.browse_num,
                        hold_num = o.hold_num,
                        down_number = o.down_number,
                        pay_num=o.pay_num,
                        talk_num = o.talk_num,
                        file_status = o.file_status,
                        allow_edit = o.allow_edit,
                        spread_url = (!string.IsNullOrEmpty(o.spread_url)) ? o.service_ip + o.spread_url : string.Empty,//宣传地址
                        video_url = o.video_url,//录屏地址
                        folder_limit = o.folder_limit,
                        pro_form = o.pro_form,
                        isPay = o.isPay,
                        isfree = o.isfree,
                        folder_author = o.folder_author,
                        update_time = o.update_time,
                        share_num = o.share_num,
                        option_size = o.option_size,
                        proType = o.proType,
                        supplyType = o.supplyType,
                        approve_time = o.approve_time,
                        folder_id = o.folder_id,
                        folder_pro_type = o.folder_pro_type,
                        works_pro_type = o.works_pro_type,
                        picture_id = o.picture_id,
                        approve_note = o.approve_note
                    };
                    //统计学习人数

                    //附件列表
                    List<T_DocFileOptions> options = new List<T_DocFileOptions>();
                    if (o.pageType.Equals("VRWorks"))
                    {
                        var t = DBSession.IT_DocFileOptionsDAL.Select(s => s.file_id == o.file_id).OrderByDescending(s => s.create_date).FirstOrDefault();
                        if (t != null)
                            options.Add(t);
                    }
                    else
                        options = DBSession.IT_DocFileOptionsDAL.Select(s => s.file_id == o.file_id);
                    m.prefixUrl = GetServiceUrl(options?.FirstOrDefault()?.service_id);
                    if (model.fileStatus == 0 || model.fileStatus == 1)
                    {
                        //附件列表
                        options.ForEach(item =>
                        {
                            if (!string.IsNullOrEmpty(item.option_url) && !string.IsNullOrEmpty(item.service_id))
                            {
                                string serviceUrl = GetServiceUrl(item.service_id);
                                if (!string.IsNullOrEmpty(serviceUrl))
                                    item.option_url = serviceUrl + item.option_url;
                            }
                        });
                        m.fileOption = options;
                    }else
                    {
                        //附件列表，仅填充service_id
                        options.ForEach(item =>
                        {
                            item.option_url = "";
                            item.file_suffix = "";
                            item.option_plat = "";
                            item.head_facility = "";
                        });
                        m.fileOption = options;
                    }
                    int allCount = m.result_ok + m.result_error;
                    if (m.result_error == 0 && allCount>0)
                        m.accuracy = 100;
                    else if(allCount > 0)
                    {
                        var _result = float.Parse(m.result_ok.ToString()) / float.Parse((m.result_ok + m.result_error).ToString());
                        m.accuracy = (int)(Math.Round(_result, 2) * 100);
                    }
                    if (!string.IsNullOrEmpty(o.user_head))
                        m.user_head = o.user_head?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    if (!string.IsNullOrEmpty(o.picture))
                        m.picture = o.picture?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    List<T_VRGoodDisiPrice> q = query.Where(s => s.file_id == o.file_id)?.OrderBy(s => s.op_month).ToList();
                    //原始价格明细
                    List<GoodsPriceModel> priceList = new List<GoodsPriceModel>();
                    //折扣价格明细
                    List<GoodsPriceModel> rateList = new List<GoodsPriceModel>();
                    q.ForEach(s => {
                        priceList.Add(new GoodsPriceModel { PurchasePeriodCode=s.op_code, price_name = s.price_name, op_month = s.op_month, op_price = s.ori_price });
                        decimal tempPrice = s.ori_price;
                        if (m.rate > 0 && m.rate <= 100)
                            tempPrice = Math.Round(tempPrice * m.rate / 100, 2);
                        rateList.Add(new GoodsPriceModel { PurchasePeriodCode = s.op_code, price_name = s.price_name, op_month = s.op_month, op_price = tempPrice });
                    });
                    m.price = priceList;
                    m.ratePrice = rateList;
                    if (priceList.Count > 0)
                        m.file_money = priceList.FirstOrDefault().op_price;
                    //缩略图
                    List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == o.file_id);
                    if (photoOption.Count > 0)
                        photoOption.ForEach(s => s.file_url = s.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                    m.photoOption = photoOption;
                    goods.Add(m);
                });
            }
            return new TableModel
            {
                rows = goods,
                total = total //DBSession.IT_DocumentInfoDAL.GetAPPShopCount(model, userId)
            };
        }
        /// <summary>
        ///  获取我的资源/作品 List<GoodsListModel>
        /// </summary>
        /// <param name="folderId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<GoodsListModel> GetSynchronMyVR(DocListParam model, int userId)
        {
            return DBSession.IT_DocumentInfoDAL.GetSynchronMyVR(model, userId);
        }
        /// <summary>
        ///  获取我的资源/作品
        /// </summary>
        /// <param name="folderId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public TableModel GetSynchronMyVRData(DocListParam model, int userId)
        {
            List<GoodsListModel> result = DBSession.IT_DocumentInfoDAL.GetSynchronMyVR(model, userId);
            List<int> fileIds = result.Select(s => s.file_id)?.ToList();
            List<MyGoodsModel> goods = new List<MyGoodsModel>();
            if (fileIds != null && fileIds.Count > 0)
            {
                string temp = string.Join(",", fileIds.ToArray());
                List<T_VRGoodDisiPrice> query = DBSession.IT_VRGoodDisiPriceDAL.Select(s => temp.Contains(s.file_id.ToString()));
                result.ForEach(o =>
                {
                    //附件列表
                    List<T_DocFileOptions> options = new List<T_DocFileOptions>();
                    if (!string.IsNullOrEmpty(o.pageType) && o.pageType.Equals("VRWorks"))
                    {
                        var t = DBSession.IT_DocFileOptionsDAL.Select(s => s.file_id == o.file_id).OrderByDescending(s => s.create_date).FirstOrDefault();
                        if (t != null)
                            options.Add(t);
                    }else
                         options = DBSession.IT_DocFileOptionsDAL.Select(s => s.file_id == o.file_id);
                    MyGoodsModel m = new MyGoodsModel
                    {
                        is_entity = o.is_entity,
                        learn_num = o.learn_num,
                        topic_num = o.topic_num,
                        result_ok = o.result_ok,
                        result_error = o.result_error,
                        file_order = o.file_order,
                        pageType = o.pageType,
                        file_code = o.file_code,
                        org_unit = o.org_unit,
                        file_id = o.file_id,
                        file_name = o.file_name,
                        alias_name = o.alias_name,
                        file_note = o.file_note,
                        //file_money = o.file_money,
                        vr_star = o.vr_star,
                        self_star = o.self_star,
                        file_classify = o.file_classify,
                        is_get = o.is_get,
                        is_hold = o.is_hold,
                        create_time = o.create_time,
                        create_name = o.create_name,
                        create_id = o.create_id,
                        browse_num = o.browse_num,
                        hold_num = o.hold_num,
                        down_number = o.down_number,
                        talk_num = o.talk_num,
                        file_status = o.file_status,
                        allow_edit = o.allow_edit,
                        spread_url = (!string.IsNullOrEmpty(o.spread_url)) ? o.service_ip + o.spread_url : string.Empty,//宣传地址
                        video_url = o.video_url,//录屏地址
                        folder_limit = o.folder_limit,
                        pro_form = o.pro_form,
                        isPay = o.isPay,
                        isfree = o.isfree,
                        folder_author = o.folder_author,
                        update_time = o.update_time,
                        share_num = o.share_num,
                        option_size = o.option_size,
                        proType = o.proType,
                        supplyType = o.supplyType,
                        approve_time = o.approve_time,
                        folder_id = o.folder_id,
                        folder_pro_type = o.folder_pro_type,
                        works_pro_type = o.works_pro_type,
                        picture_id = o.picture_id,
                        approve_note = o.approve_note
                    };
                    //附件列表
                    options.ForEach(item =>
                    {
                        if (!string.IsNullOrEmpty(item.option_url) && !string.IsNullOrEmpty(item.service_id))
                        {
                            string serviceUrl = GetServiceUrl(item.service_id);
                            if (!string.IsNullOrEmpty(serviceUrl))
                                item.option_url = serviceUrl + item.option_url;
                        }
                    });
                    m.fileOption = options;
                    //前缀
                    m.prefixUrl = GetServiceUrl(options?.FirstOrDefault()?.service_id);
                    int allCount = m.result_ok + m.result_error;
                    if (m.result_error == 0 && allCount > 0)
                        m.accuracy = 100;
                    else if (allCount > 0)
                    {
                        var _result = float.Parse(m.result_ok.ToString()) / float.Parse((m.result_ok + m.result_error).ToString());
                        m.accuracy = (int)(Math.Round(_result, 2) * 100);
                    }
                    if (!string.IsNullOrEmpty(o.user_head))
                        m.user_head = o.user_head?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    if (!string.IsNullOrEmpty(o.picture))
                        m.picture = o.picture?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    List<T_VRGoodDisiPrice> q = query.Where(s => s.file_id == o.file_id)?.OrderBy(s => s.op_month).ToList();
                    List<GoodsPriceModel> priceList = new List<GoodsPriceModel>();
                    q.ForEach(s => {
                        priceList.Add(new GoodsPriceModel { op_month = s.op_month, op_price = s.ori_price });
                    });
                    m.price = priceList;
                    if (priceList.Count > 0)
                        m.file_money = priceList.FirstOrDefault().op_price;
                    //缩略图
                    List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == o.file_id);
                    if (photoOption.Count > 0)
                        photoOption.ForEach(s => s.file_url = s.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                    m.photoOption = photoOption;
                    goods.Add(m);
                });
            }
            return new TableModel
            {
                rows = goods,
                total = GetSynchronMyVRCount(model, userId)
            };
        }

        private string GetServiceUrl(string service_id)
        {
            if (string.IsNullOrEmpty(service_id))
                return string.Empty;
            T_ItemCode code = DBSession.IT_ItemCodeDAL.FindSingle(s => s.item_code.Equals("docFileService"));
            List<T_ItemCodeMenum> serviceList = null;
            if (null != code)
                serviceList = DBSession.IT_ItemCodeMenumDAL.Select(s => s.item_id == code.item_id);
            if (null == serviceList || serviceList.Count <= 0)
                return string.Empty;
            return serviceList.Where(s => s.code_name.Equals(service_id)).FirstOrDefault()?.code_value;
        }
        /// <summary>
        ///  统计我的资源/作品 数量
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetSynchronMyVRCount(DocListParam model, int userId)
        {
            return DBSession.IT_DocumentInfoDAL.GetSynchronMyVRCount(model, userId);
        }
        /// <summary>
        ///  判断用户是否购买过此商品
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool PayCountByFileId(int fileId, int userId)
        {
            int mark = DBSession.IT_DocumentInfoDAL.PayCountByFileId(fileId, userId);
            return mark > 0 ? true : false;
        }
        /// <summary>
        ///  判断文件是否有被分享给用户没有
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool ShareFileToUser(int fileId, int userId)
        {
            int mark = DBSession.IT_DocumentInfoDAL.ShareFileToUser(fileId, userId);
            return mark > 0 ? true : false;
        }
        /// <summary>
        ///  判断用户是否拥有审核权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool IsApproveLimit(int userId)
        {
            List<int> list = DBSession.IT_PermissionsDAL.GetPermissById(userId)?.Select(s => s.per_id)?.ToList();
            if (list == null || list.Count <= 0)
                return false;
            if (DBSession.IT_DocumentInfoDAL.IsApproveLimit(list) > 0)
                return true;
            return false;
        }

        /// <summary>
        ///  获取附件地址
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public PayDocFileOptionsModel GetBagFileRecord(int file_id)
        {
            return DBSession.IT_DocumentInfoDAL.GetBagFileRecord(file_id);
        }
        /// <summary>
        ///  获取商品购买使用截止时间
        /// </summary>
        /// <param name="file_id"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public PayNorderModel GetFileEndTime(int file_id, int user_id)
        {
            return DBSession.IT_DocumentInfoDAL.GetFileEndTime(file_id, user_id);
        }
        /// <summary>
        ///  批量删除作品时记录删除附件信息
        /// </summary>
        /// <param name="fileIds"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public bool RecordDelBatchFile(List<int> fileIds,string user_name)
        {
            if (fileIds == null || fileIds.Count <= 0)
                return false;
            List<DelRecordOption> list = DBSession.IT_DocumentInfoDAL.GetFildDelRecord(fileIds);
            if (list == null || list.Count <= 0)
                return true;
            list.ForEach(o => DBSession.IT_VRDelAffixRecordDAL.Add(new T_VRDelAffixRecord
            {
                option_url = o.option_url,
                service_url = o.code_value,
                del_name = user_name,
                del_date = DateTime.Now
            }));
            return true;
        }
        /// <summary>
        ///  判断是否允许被删除
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public int CheckDelFile(int file_id)
        {
            return DBSession.IT_DocumentInfoDAL.CheckDelFile(file_id);
        }
        /// <summary>
        ///  获取用户收藏的商品和作品
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<OutputUserFavorite> GetUserFavorite(UserFavorite param,int user_id)
        {
            List<OutputUserFavorite> list = new List<OutputUserFavorite>();
            var obj = DBSession.IT_DocumentInfoDAL.GetUserFavorite(param, user_id);
            obj?.ForEach(o =>
            {
                OutputUserFavorite temp = new OutputUserFavorite { file_id=o.file_id,file_name=o.file_name};
                //缩略图
                List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == o.file_id);
                if (photoOption.Count > 0)
                    photoOption.ForEach(s => s.file_url = s.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                temp.photoOption = photoOption;
                list.Add(temp);
            });
            return list;
        }
        /// <summary>
        ///  获取用户浏览历史
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<OutputUserBrowse> GetUserBrowse(InputUserBrowseParam param)
        {
            List<OutputUserBrowse> list = new List<OutputUserBrowse>();
            var obj = DBSession.IT_DocumentInfoDAL.GetUserBrowse(param);
            obj?.ForEach(o =>
            {
                OutputUserBrowse temp = new OutputUserBrowse
                {
                    name = o.name,
                    id = o.id,
                    b_type = o.b_type,
                    create_date = o.create_date
                };
                //价格
                if(o.b_type==1 || o.b_type == 3)
                {
                    //商品、作品
                    var p = DBSession.IT_VRGoodDisiPriceDAL.Select(s => s.file_id == o.id);
                    List<PriceList> price = new List<PriceList>();
                    p?.ForEach(n => price.Add(new PriceList { op_month = n.op_month, price_name = n.price_name, ori_price = n.ori_price }));
                    temp.price = price;
                    //缩略图
                    var photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == o.id);
                    List<PictureList> photo = new List<PictureList>();
                    photoOption?.ForEach(n => photo.Add(new PictureList { url = n.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) }));
                    temp.photoOption = photo;
                }
                else
                {
                    //目录封面
                    string photoOption = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == o.id)?.folder_url;
                    List<PictureList> photo = new List<PictureList>();
                    if (!string.IsNullOrEmpty(photoOption))
                        photo.Add(new PictureList { url = photoOption.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) });
                    temp.photoOption = photo;
                }
                list.Add(temp);
            });
            return list;
        }
        /// <summary>
        ///  获取我的收藏商品列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<OutputMyGoods> GetMyGoodsFavorite(InputMyGoods param, int user_id)
        {
            List<OutputMyGoods> list = new List<OutputMyGoods>();
            var obj = DBSession.IT_DocumentInfoDAL.GetMyGoodsFavorite(param, user_id);
            int year = DateTime.Now.Year;
            var levelHelper = new T_VRUserLevelBLL();
            obj?.ForEach(o=> {
                OutputMyGoods temp = o.ToOutputMyGoods();
                //商品价格
                var p = DBSession.IT_VRGoodDisiPriceDAL.Select(s => s.file_id == o.fileID);
                List<PriceList> filePrice = new List<PriceList>();
                p?.ForEach(n => filePrice.Add(new PriceList { op_month = n.op_month, price_name = n.price_name, ori_price = n.ori_price }));
                temp.filePrice = filePrice;
                //折扣价格
                //获取用户折扣率
                UserLevelColumn level = levelHelper.ResetUserLevel(user_id, o.folderID, year);//用户在目录下的等级
                decimal rate = levelHelper.GetGoodRate(level.userLevel, o.fileID, o.folderID);//获取商品折扣
                temp.ratePrice = filePrice;
                if (rate > 0)
                    temp.ratePrice?.ForEach(n => n.ori_price = Math.Round(n.ori_price * rate / 100, 2));
                //缩略图
                List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(s => s.file_id == o.fileID);
                if (photoOption.Count > 0)
                    photoOption.ForEach(s => s.file_url = s.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                temp.photoOption = photoOption;
                list.Add(temp);
            });
            return list;
        }
        /// <summary>
        ///  获取店铺商品列表
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<OutputGoodsByStore> GetGoodsByStoreList(InputGoodsByStore param, int user_id, out int total)
        {
            var list = DBSession.IT_DocumentInfoDAL.GetGoodsByStoreList(param, user_id,out total);
            list?.ForEach(s=> {
                //商品最低折扣价
                if (s.rate0 > 0 && s.rate0 <= 10)
                    s.ratePrice = Math.Round(s.filePrice * s.rate0 / 10, 2);
                else
                    s.ratePrice = s.filePrice;
                //最低价格
                s.minPrice = s.filePrice;
                //商品横向缩略图
                if (!string.IsNullOrEmpty(s.fileImage))
                    s.fileImage = s.fileImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                //获取商品规格
                //var obj = DBSession.IT_VRDDGoodSpecificationDAL.Select(o => o.file_id == s.file_id);
                //度度圈新规格信息
                var obj = DBSession.IT_DocumentInfoDAL.GetSpecInfo(s.file_id);
                List<GoodsSizeModel> spec = new List<GoodsSizeModel>();
                obj?.ForEach(n => spec.Add(new GoodsSizeModel { specName = n.specName, specOption = n.specOption }));
                s.specList = spec.Count > 0 ? spec : null;
            });
            return list;
        }
    }
}